/**
 * Copyright (C), 2015-2020, XXX有限公司
 * <p>
 * FileName: MyFilter
 * <p>
 * Author:   Brill
 * <p>
 * Date:     2020/2/29/029 14:16
 * <p>
 * Description: 用户过滤器,查询访问的接口需要什么样的角色
 * <p>
 * History:
 *
 * <author>          <time>          <version>          <desc>
 * <p>
 * 作者姓名           修改时间           版本号              描述
 */


package cn.yuhh.config;


import cn.yuhh.entity.Menu;
import cn.yuhh.entity.Role;
import cn.yuhh.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈用户过滤器,查询访问的接口需要什么样的角色〉
 *
 * @author Brill

 * @create 2020/2/29/029

 * @since 1.0.0

 */

@Component
public class MyFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = this.menuService.getAllMenusWithRole();

        for (Menu menu : menus) {
            if (pathMatcher.match(menu.getUrl(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                String[] str = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i).getName();
                }

                return SecurityConfig.createList(str)       ;

            }
        }

        return SecurityConfig.createList("ROLE_LOGIN");


    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
